import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @description:
 * @Author: wuzhenbin
 * @CreateTime: 2025/2/16
 */
public class leetcode_102 {
    public static void main(String[] args) {

    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public List<List<Integer>> levelOrder(TreeNode root) {
        if (root == null) {
            return new ArrayList<List<Integer>>();  // 如果树为空，返回空列表
        }

        Queue<TreeNode> queue = new LinkedList<>();
        List<List<Integer>> list = new ArrayList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            ArrayList<Integer> list1 = new ArrayList<>();
            ArrayList<TreeNode> list2 = new ArrayList<>();
            while(!queue.isEmpty()){
                TreeNode poll = queue.poll();
                list1.add(poll.val);
                list2.add(poll);
            }
            for (TreeNode father : list2) {
                if (father!=null&&father.left != null) queue.add(father.left);
                if (father!=null&&father.right != null) queue.add(father.right);
            }
            list.add(list1);
        }
        return list;
    }
}
